use std::sync::Arc;
use tokio::io::{ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tokio::sync::{mpsc, Mutex};

use crate::proto::War3Message;
use super::split_tcp::{split_tcp_stream, SplitTcp};

/// 客户端连接
/// 使用split后的读写半部分，避免锁竞争
pub struct ClientConnection {
    read_half: Arc<Mutex<ReadHalf<TcpStream>>>,
    write_half: Arc<Mutex<WriteHalf<TcpStream>>>,
    send_queue: mpsc::UnboundedSender<War3Message>,
}

impl ClientConnection {
    /// 创建新的ClientConnection
    /// 返回ClientConnection实例和消息接收器
    pub fn new(stream: TcpStream) -> (Self, mpsc::UnboundedReceiver<War3Message>) {
        let (read_half, write_half) = split_tcp_stream(stream);
        let (send_tx, send_rx) = mpsc::unbounded_channel();
        
        (
            Self {
                read_half,
                write_half,
                send_queue: send_tx,
            },
            send_rx,
        )
    }
    
    /// 获取发送队列的发送器
    pub fn sender(&self) -> mpsc::UnboundedSender<War3Message> {
        self.send_queue.clone()
    }
}

impl SplitTcp for ClientConnection {
    fn read_half(&self) -> Arc<Mutex<ReadHalf<TcpStream>>> {
        Arc::clone(&self.read_half)
    }
    
    fn write_half(&self) -> Arc<Mutex<WriteHalf<TcpStream>>> {
        Arc::clone(&self.write_half)
    }
}
